/*
 * =====================================================================================
 *
 *       Filename:  SocketMgrLinux.h
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2012-10-01
 *       Revision:  none
 *       Compiler:  cmake & gcc
 *
 *         Author:  ankjt
 *
 * =====================================================================================
 */

#ifndef __SOCKETMGR_LINUX_H__
#define __SOCKETMGR_LINUX_H__

#include "SocketDefines.h"
#include "Thread.h"
#include "Socket.h"
#include "TeNetMgr.h"


#define SOCKET_HOLDER_SIZE 30000   
#define THREAD_EVENT_SIZE 4096     

class SocketWorkerThread;
class ListenSocketBase;

class SocketMgr
{
 public:
    friend class SocketWorkerThread;

    SocketMgr(TeNetCall* pkCall);
    ~SocketMgr();

    bool Init();
    void Update();

    TeNetCall* GetCall(){ return m_pkCall;}

    void AddSocket(Socket* s);
    void RemoveSocket(Socket* s);

    inline int GetEpollFd() { return m_EpollFd; }
    inline Socket* GetSocket(int iFd){ m_pkFds[iFd];}

    bool SendBuffer(SOCKET sFd,void* pData,int iSize);

    void PushSocket(Socket* s);

    void DisConnect(SOCKET sFd);

    void CloseAll();

    void SpawnWorkerThreads();

private:
    int m_EpollFd;

    Socket* m_pkFds[SOCKET_HOLDER_SIZE];
    SocketWorkerThread* m_pkSocketThread;

    TeNetCall* m_pkCall;

    TReadWriteBuffer m_kSocketBuffer;

};

class SocketWorkerThread : public Thread
{
    struct epoll_event m_kEvents[THREAD_EVENT_SIZE];
    bool m_bRunning;

    SocketMgr*	m_pkMgr;
public:
    SocketWorkerThread(SocketMgr* pkMgr)
    {
        m_pkMgr = pkMgr;
    }
    void Run();
    void OnShutdown()
    {
        m_bRunning = false;
    }
};

#endif
